package com.lsh.user.controller;

import com.google.code.kaptcha.Producer;
import com.lsh.common.constant.Constants;
import com.lsh.common.redis.RedisCache;
import com.lsh.common.util.AjaxResult;
import com.lsh.common.util.Base64;
import com.lsh.common.util.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * @Date 2021年09月15日16:46:08
 * @Author  LiuShihao
 */
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 验证码类型
    @Value("${captcha.type}")
    private String captchaType;

    /**
     * 生成验证码
     * @param response
     * @return UUID 本次图片验证码唯一标识
     * @return img  图片验证码Base64编码
     * @throws IOException
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        System.out.println("code:"+code+" , uuid:"+uuid);
//        stringRedisTemplate.opsForValue().set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
//        System.out.println("img:"+Base64.encode(os.toByteArray()));
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));

        return ajax;
    }

    /**
     * Base64编码转图片
     * @param map 图片验证码Base64编码
     * @return 验证码图片
     * @throws Exception
     */
    @GetMapping("/saveCaptchaImage")
    public void saveCaptchaImage(@RequestBody Map<String,Object> map,HttpServletResponse response) throws Exception {
        String base64Img =(String) map.get("img");
        byte[] decode = Base64.decode(base64Img);
        File file = new File("./img.jpg");
        ByteArrayInputStream in = new ByteArrayInputStream(decode);
        FileOutputStream fos = new FileOutputStream(file);
        FastByteArrayOutputStream fastByteArrayOutputStream = new FastByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        while (in.read(bytes) != -1){
            fos.write(bytes);
            fastByteArrayOutputStream.write(bytes);
        }
        in.close();
        fos.close();
        System.out.println("===完成===");

    }

    /**
     * 直接将图片的文件流响应到前端
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/getCaptchaImage")
    public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File("./img.jpg");
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("image/jpg");
        byte[] bytes = new byte[1024];

        while (fis.read(bytes) != -1){
            os.write(bytes);
        }
        fis.close();
        os.close();

        System.out.println("===完成===");
    }
}
